import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import { config } from '@/config/index.js';
import { langs } from '@/locale/language.js';
import { utils, storage } from '@/utils/index.js';
import apis from '@/apis/apis';

export const useWebSocketStore = defineStore('webSocket', () => {
	const token = computed(() => loginStore().token);
	const userInfo = computed(() => loginStore().userInfo);
	const langInfo = computed(() => setupsStore().langInfo);

	const socket = ref();           // websocket
	const isConnected = ref(false); // 是否连接了websocket
	const botMsg = ref(null);        // AI BOT回复的实时消息体
	const messageQueue = ref(null);  // 断开websocket后，重新连接前未发送消息的对列
	
	let loading = false;
	
	// 建立 WebSocket
	function connectSocket () {
		getConnectSocket();
		
		// 监听 socket 事件等等
		uni.onSocketOpen(() => {
			console.log('Socket1 连接成功');
			isConnected.value = true;
			
			if (messageQueue.value) {
				sendMsgHandler(messageQueue.value);
				
				messageQueue.value = null;
			}
		});
		
		uni.onSocketClose(() => {
			console.log('Socket 连接已关闭');
			disconnectSocket();
		});
		
		uni.onSocketError((err) => {
			console.error('Socket 连接出错：', err);
			disconnectSocket();
		});
		
		uni.onSocketMessage((res) => {
			const msg = JSON.parse(res.data);
			
			// console.log(msg);
			
			if (msg.sender === "bot") {
				if (msg.type === 'start') {
					if (!botMsg.value) {
						botMsg.value = {
							sender: 'bot',
							children: [],
							message: '',
							loadingText: true,
							msg_id: ''
							// id: utils.generateRandomId()
						}
					}
				} else if (msg.type === 'stream') {
					botMsg.value.children.push(msg);
					botMsg.value.message += msg.message;
					botMsg.value.message = botMsg.value.message.replace(/\n/g, "<br>");
					
					// 渲染在页面上的数据
					botMsg.value.msg = botMsg.value.message.replace(/⎈/g, "");
					botMsg.value.msgList = botMsg.value.msg.split(/<br>/g).filter(item => item);
					
					botMsg.value.loadingText = false;
				} else if (msg.type === 'info') {
				} else if (msg.type === 'update') {
					botMsg.value.msg_id = JSON.parse(msg.message).message_list[1].msg_id;
				} else if (msg.type === 'error') {
					botMsg.value.loadingText = false;
					botMsg.value = null;
				} else if (msg.type === 'end') {
					botMsg.value.message = botMsg.value.message.replace(/⎈/g, "");
					
					botMsg.value = null;
					loading = false;
				}
			} else {
				// msg.id = utils.generateRandomId();
			}
		});
	}
	
	function processHtmlString(htmlString) {
		// 匹配类似&lt;h1>或&lt;/h1>的模式，其中h1可以是任意标签名
		const pattern = /&lt;(\/?[a-zA-Z][^\s>]*)>/g;

		// 使用replace方法进行替换
		const processedHtml = htmlString.replace(pattern, (match, p1) => {
			p1 = p1.replace('h1', 'h3');
			return '<' + p1 + '>'; // 将&lt;h1>或&lt;/h1>转换为<h1>或</h1>
		});

		return processedHtml;
	}
	
	function getConnectSocket() {
		try {
			if (isConnected.value) {
				console.log('WebSocket 已连接');
				return; // 如果已连接，则不执行连接操作
			}
			
			if (token.value) {
				const params = {
					jwt: token.value,
					cuid: userInfo.value.cuid,
					belief_system: 'Evangelicalism',
					style: 'Story-Driven'
				};

				socket.value = uni.connectSocket({
					// WebSocket URL
					url: `${config.WS}?${utils.urlSearchParams(params)}`,
					// 其他配置项
				});
			}
			
		} catch (error) {
			console.error('连接 Socket 出错：', error);
			disconnectSocket();
			throw error;
		};
	}
	
	// 断开 WebSocket 
	function disconnectSocket() {
		if (isConnected.value) {
	        uni.closeSocket();
			socket.value = null;
	        isConnected.value = false;
			
			messageQueue.value = null;
			botMsg.value = null;
	    }
	}
	
	// 发送消息
	async function sendMsg(msg, params = {}) {
		/*  params
			场景ID      	scenario_id    祷告助手10001   问答助手10007   解经助手10008
			内容ID      	tag_id || book_id   
			语言版本    	language
			            belief_system 
						denomination
						style
		*/
		const obj = {
			question: msg,
			ref_data: {...params, language: langInfo.value.type }
		};
		
		if (socket.value && isConnected.value) {
			sendMsgHandler(obj);
		} else {
			messageQueue.value = obj;
			getConnectSocket();
		}
		
		if (!botMsg.value) {
			botMsg.value = {
				sender: 'bot',
				children: [],
				message: '',
				loadingText: true,
				msg_id: ''
				// id: utils.generateRandomId()
			}
		}
	}
	
	function sendMsgHandler(obj) {
		uni.sendSocketMessage({
			data: JSON.stringify(obj)
		});
	}

	// 获取历史会话消息
	async function getHistory(params) {
		return await apis.getHistory(params);
	}
	
	// 对历史消息进行处理，以符合渲染的数据格式
	function historyMsgHandler(lists) {
		return lists.map((item, index) => {
			item.msg = utils.removeMarkdownTags(item.content);
			item.content = item.content.replace(/<br>/g, " ");
			// item.voice = item.copy.replace(/\n/g, "  ");
			item.content = item.content.replace(/\n/g, "<br>");
			item.msgList = item.msg.replace(/⎈/g, "").replace(/§/g, "").split(/\n/g).filter(item => item);
			return {
				msg_id: item.msg_id || item.id,
				sender: item.sender_cuid != userInfo.value.cuid ? 'bot' : 'you',
				message: item.content,
				msg: item.msg,
				msgList: item.msgList,
				date: item.create_at,
				type: "stream"
			};
		})
	}
	
	// 对实时消息进行处理
	function socketMsgHandler(msg) {
		loading = true;
		return {
			// id: utils.generateRandomId(),
			sender: 'you',
			message: msg,
			type: "stream"
		}
	}
	
	function removeMarkdownTags(str, flag) {
		// 去掉 Markdown 标签（如 **，__，*，_，# 等）
		// return str.replace(/[\w]*(\*+|#+|>+|`+|\-+|\++|~~+)/g, '');
		
		if (!flag) {
			// 保留 H1~H6 的 Markdown 转换为 HTML
			str = str.replace(/^\s*(#{1,6})\s*(.+?)\s*$/gm, (match, p1, p2) => {
				const level = p1.length;
				return `<h${level}>${p2}</h${level}>`;
			});
			// str = str.replace(/^(#{1,6})\s*(.+)$/gm, (match, p1, p2) => {
			// 	const level = p1.length;
			// 	return `<h${level}>${p2}</h${level}>`;
			// });

			// 保留加粗 ** 或 __
			str = str.replace(/(\*\*|__)(.*?)\1/g, '<b>$2</b>'); // 加粗

			// 保留斜体 * 或 _
			str = str.replace(/(\*|_)(.*?)\1/g, '<i>$2</i>'); // 斜体
		}
		
		// 去掉其他不必要的 Markdown 标签
		str = str.replace(/~~(.*?)~~/g, ''); // 删除线
		str = str.replace(/`([^`]+)`/g, ''); // 行内代码
		str = str.replace(/```[\s\S]*?```/g, ''); // 代码块
		
		return str;
		// return str.replace(/(\*\*|__|\*|_|`|~~|#+|\[|\]|\(|\))/g, '');
	}
	
	function removeATags(str) {
		// 去掉 <a> 标签，保留其中的文本内容
		return str.replace(/<a[^>]*>([^<]*)<\/a>/g, '$1');
	}
	
	return {
		socket,
		botMsg,
		sendMsg,
		isConnected,
		connectSocket,
		disconnectSocket,
		historyMsgHandler,
		socketMsgHandler,
		getHistory
	};
});